﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Configuration.Provider;
using System.Web.Hosting;
using System.ServiceModel;
using SSOClientServices.SSOWebService;
using System.ServiceModel.Channels;
using System.Diagnostics;

namespace SSOClientServices
{
    public class SSOMembershipProvider:MembershipProvider
    {
        
        
        private SSOWebService.SSOClient proxy;
        private string GetConfigValue(string configValue, string defaultValue)
        {
            if (String.IsNullOrEmpty(configValue))
                return defaultValue;

            return configValue;
        }
        private const string providerName = "SSOMembershipProvider";
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            try
            {
                
                if (config == null)
                    throw new ArgumentNullException("configuration");

                if (name == null || name.Length == 0)
                    name = providerName;

                if (String.IsNullOrEmpty(config["description"]))
                {
                    config.Remove("description");
                    config.Add("description", "Single Sign On Membership provider");
                }
                base.Initialize(name, config);
                pEndPointUri = GetConfigValue(config["endPointUri"], "");
                pApplicationName = GetConfigValue(config["applicationName"], HostingEnvironment.ApplicationVirtualPath);
                pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5"));
                pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10"));
                pMinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1"));
                pMinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7"));
                pPasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], ""));
                pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true"));
                pEnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true"));
                pRequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false"));
                pRequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true"));
                pWriteExceptionsToEventLog = Convert.ToBoolean(GetConfigValue(config["writeExceptionsToEventLog"], "true"));

                // Initialise end point
                BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None)
                {
                    Name = "BasicHttpBinding_ISSO",
                    TransferMode = TransferMode.Buffered
                , AllowCookies=false, BypassProxyOnLocal = true, HostNameComparisonMode=HostNameComparisonMode.StrongWildcard,
                 MessageEncoding= WSMessageEncoding.Text , TextEncoding = Encoding.UTF8,
                UseDefaultWebProxy = true
                
                };
                binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
                binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
                binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
                EndpointAddress address= new EndpointAddress(pEndPointUri); 
                
                proxy = new SSOWebService.SSOClient(binding, address);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Application", ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
            
        }
        public override string ApplicationName
        {
            get
            {
                return pApplicationName;
            }
            set
            {
                pApplicationName = value;
            }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            return proxy.ChangePassword(username, oldPassword, newPassword);
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotSupportedException("Change password is not supported. you must reset the password.");
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            try
            {
                proxy.CreateUser(username, password,  email, isApproved);
                status = MembershipCreateStatus.Success;
            }

            catch (FaultException<SSOUserAlreadyExistsException> ex)
            {
                status = MembershipCreateStatus.DuplicateEmail;
                throw ex;
            }
            catch (Exception ex)
            {
                status = MembershipCreateStatus.ProviderError;
                throw ex;
            }
            
            return null; 
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            bool result = true;
            try
            {
                proxy.DeleteUser(username);
            }
            catch (FaultException<SSOUserAlreadyExistsException> ex)
            {
                result = false;
                throw ex;
            }
            return result;
        }

        public override bool EnablePasswordReset
        {
            get { return true; }
        }

        public override bool EnablePasswordRetrieval
        {
            get { return false; }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection result = new MembershipUserCollection();
            var userList = proxy.FindUsersByEmail(emailToMatch).ToList();
            totalRecords = userList.Count;
            userList.ForEach(delegate(AuthenticatedUser usr)
            {
                result.Add(UserToMembershipUser(usr));
            });
            return result;
        }

        private MembershipUser UserToMembershipUser(AuthenticatedUser usr)
        {
            
            MembershipUser memUser = new MembershipUser(this.Name, usr.UserName, usr.Key, usr.Email,"","",usr.IsActive, 
                !usr.IsActive,  usr.CreationDate = DateTime.Now, usr.LastLoginDate, usr.LastLoginDate,
                usr.LastPasswordChangeDate, usr.LastLockOutDate);
            return memUser;
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection result = new MembershipUserCollection();
            var userList = proxy.FindUsersByName(usernameToMatch).ToList();
            totalRecords = userList.Count;
            userList.ForEach(delegate(AuthenticatedUser usr)
            {
                result.Add(UserToMembershipUser(usr));
            });
            return result;
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection result = new MembershipUserCollection();
            var userList = proxy.GetUsers(pageIndex, pageSize).ToList(); 
            totalRecords = userList.Count;
            userList.ForEach(delegate(AuthenticatedUser usr)
            {
                result.Add(UserToMembershipUser(usr));
            });
            return result;
        }

        public override int GetNumberOfUsersOnline()
        {
            return proxy.GetOnlineCount(); 
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotSupportedException("Only password reset is supported.");
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            var usr = proxy.GetUserByName(username);
            return UserToMembershipUser(usr);
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            int id = (int)providerUserKey;
            return UserToMembershipUser(proxy.GetUserByID(id));
        }

        public override string GetUserNameByEmail(string email)
        {
            return proxy.GetUserByEmail(email).UserName;
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { return pMaxInvalidPasswordAttempts; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return pMinRequiredNonAlphanumericCharacters; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return pMinRequiredPasswordLength; }
        }

        public override int PasswordAttemptWindow
        {
            get { return pPasswordAttemptWindow; }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { return MembershipPasswordFormat.Hashed; }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { return pPasswordStrengthRegularExpression; }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return pRequiresQuestionAndAnswer; }
        }

        public override bool RequiresUniqueEmail
        {
            get { return pRequiresUniqueEmail; }
        }

        public override string ResetPassword(string username, string answer)
        {
            string resultPassword = "";
            try
            {
                if (!pEnablePasswordReset)
                    throw new NotSupportedException("Password reset not supported.");
                 PasswordResetResultType result = proxy.ResetPassword(this.GetUser(username, true).Email);
                 if (result == PasswordResetResultType.EmailNotFound)
                     throw new ArgumentException("Email address not found.");
                 if (result == PasswordResetResultType.Error)
                     throw new Exception("could not reset password. Check system event log.");
                 resultPassword = "A new password was generated and sent to the given email address.";
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("Application", ex.Message);
                EventLog.WriteEntry("Application", ex.StackTrace);
            }
            return resultPassword;
        }

        public override bool UnlockUser(string userName)
        {
            AuthenticatedUser usr = this.proxy.GetUserByName(userName);
            proxy.UpdateUser(userName, usr.Password, usr.Email, true);
            return true;
        }

        public override void UpdateUser(MembershipUser user)
        {
            var tempUsr = proxy.GetUserByName(user.UserName);
            proxy.UpdateUser(user.UserName, tempUsr.Password, user.Email, user.IsApproved && !user.IsLockedOut);
        }

        public override bool ValidateUser(string username, string password)
        {
            bool result = true;
            try
            {
                result = proxy.SignIn(username, password);
            }
            catch (FaultException<SSOInvalidPasswordException> ex)
            {
                result = false;
                // log ex.Detail.message
            }
            catch (FaultException<SSOUserDoesNotExistException> ex)
            {
                result = false;
                // log ex.Detail.message
            }

            catch (Exception ex)
            {
                result = false;
                // log message
            }
            return result;
        }

        public string pApplicationName { get; set; }

        public int pMaxInvalidPasswordAttempts { get; set; }

        public int pPasswordAttemptWindow { get; set; }

        public int pMinRequiredNonAlphanumericCharacters { get; set; }

        public int pMinRequiredPasswordLength { get; set; }

        public string pPasswordStrengthRegularExpression { get; set; }

        public bool pEnablePasswordReset { get; set; }

        public bool pEnablePasswordRetrieval { get; set; }

        public bool pRequiresQuestionAndAnswer { get; set; }

        public bool pRequiresUniqueEmail { get; set; }

        public bool pWriteExceptionsToEventLog { get; set; }

        public string pEndPointUri { get; set; }
    }
}
